package com.mef.smsplat.eterm;


import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mef.smsplat.dao.EtermConfigInfoDao;
import com.mef.smsplat.domain.EtermConfigInfoDomain;
import com.mef.smsplat.eterm.util.EtermConfig;
import com.mef.smsplat.util.ApplicationContextUtil;
import com.swcares.clientAPI.agentAPI.CrackDriver;
import com.swcares.clientAPI.agentAPI.Driver;

public class Eterm implements IEterm {
	private static final Log logger=LogFactory.getLog(Eterm.class);
	
	/** 服务器IP */
	private static String SERVER_IP="127.0.0.1";
	/** 服务器端口 */
	private static String SERVER_PORT="9988";
	/** 配置 */
	private static List<EtermConfig> configList=new ArrayList<EtermConfig>();
	
	/** 配置--使用数据库的方式 */
	private static List<EtermConfigInfoDomain> etermConfigList=new ArrayList<EtermConfigInfoDomain>();
	
	/** 当前使用的配置 */
	private EtermConfig currentConfig;
	
	private EtermConfigInfoDomain currentEtermConfig;
	
	private Driver d = null;
	
	static{
		//启动的时候刷新配置
		init();
	}
	
	/**
	 * 初始化配置
	 */
	private static void init(){
		Properties p=new Properties();
		try {
			p.load(Eterm.class.getResourceAsStream("/eterm.properties"));
			SERVER_IP= p.getProperty("server.ip");
			SERVER_PORT=p.getProperty("server.port");
			String strConfig=p.getProperty("eterm.config");
			String strWorkcode=p.getProperty("eterm.si.workcode");
			String strPassword=p.getProperty("eterm.si.password");
			String strLevel=p.getProperty("eterm.si.level");
			if(SERVER_IP==null||"".equals(SERVER_IP.trim()))
				throw new Exception("server.ip为空");
			if(SERVER_PORT==null||"".equals(SERVER_PORT.trim()))
				throw new Exception("server.port为空");
			if(strConfig==null||"".equals(strConfig))
				throw new Exception("eterm.config为空");
			if(strWorkcode==null||"".equals(strWorkcode))
				throw new Exception("eterm.si.workcode为空");
			if(strPassword==null||"".equals(strPassword))
				throw new Exception("eterm.si.password为空");
			if(strLevel==null||"".equals(strLevel))
				throw new Exception("eterm.si.level为空");
			String[] configs=strConfig.split(",");
			String[] workcodes=strWorkcode.split(",");
			String[] passwords=strPassword.split(",");
			String[] levels=strLevel.split(",");
			if(!(configs.length==workcodes.length&&workcodes.length==passwords.length&&passwords.length==levels.length))
				throw new Exception("请检查您的eterm配置信息，个数不匹配");
				
			for(int i=0;i<configs.length;i++){
				if(configs[i]!=null&&!"".equals(configs[i].trim())){
					EtermConfig etermConfig=new EtermConfig();
					etermConfig.setConfig(configs[i]);
					etermConfig.setWorkcode(workcodes[i]);
					etermConfig.setPassword(passwords[i]);
					etermConfig.setLevel(levels[i]);
					configList.add(etermConfig);
				}
			}
		} catch (Exception e) {
			logger.error("读取eterm通信接口配置信息出错，请检查配置后刷新", e);
		}
		
		//读取数据库中的配置
		EtermConfigInfoDao  dao=(EtermConfigInfoDao)ApplicationContextUtil.getContext().getBean("etermConfigInfoDao");
		etermConfigList=dao.findAll();//查询所有
		if(etermConfigList!=null&&etermConfigList.size()>0){//数据库不为空，则替换配置文件中的配置
			configList.clear();//清空列表
			for(int i=0;i<etermConfigList.size();i++){
				EtermConfig config=new EtermConfig();
				config.setConfig(etermConfigList.get(i).getEtermConfigName());
				config.setLevel(etermConfigList.get(i).getConfigWorkLevel()+"");
				config.setPassword(etermConfigList.get(i).getConfigWorkPass());
				config.setWorkcode(etermConfigList.get(i).getConfigWorkCode());
				
				configList.add(config);
			}
		}
		
	}
	
	public void close() throws Exception {
		if(d!=null)
			d.close();

	}

	public void connect() throws Exception {
		d=new CrackDriver(SERVER_IP, Integer.parseInt(SERVER_PORT));
		d.connect();

	}

	public String send(String cmd) throws Exception {
		//随机拿到一个配置
		Random r=new Random();
		this.currentConfig=configList.get(r.nextInt(configList.size()));
		String config=currentConfig.getConfig();
		d.getSender().sendCMD(config, cmd);
		
		//这里可以记录配置的发送历史情况，基于速度的考虑，可以另外跑一个线程去执行存数据库的操作
		new Thread(new Runnable() {
			
			public void run() {
				EtermConfigInfoDao  dao=(EtermConfigInfoDao)ApplicationContextUtil.getContext().getBean("etermConfigInfoDao");
				//查找当前配置
				EtermConfigInfoDomain domain=dao.query(currentConfig.getConfig());
				if(domain!=null){
					domain.setCmdNum(domain.getCmdNum()+1);//指令数+1
					dao.update(domain);//更新到数据库
				}
			}
		}).start();
		//....
		String temp = d.getReciver().loseBoth(d.getReciver().recive());	
		//判断是否SI了
		if(temp.contains("SI")&&temp.trim().length()<5){
			//先执行SI操作
			String siCmd="SI:"+currentConfig.getWorkcode()+"/"+currentConfig.getPassword()+"/"+currentConfig.getLevel();
			d.getSender().sendCMD(config, siCmd);
			temp=d.getReciver().loseBoth(d.getReciver().recive());
			if(temp.contains("SIGNED IN")&&temp.contains("AVAIL")){
				logger.info(siCmd+"成功");
				d.getSender().sendCMD(config, cmd);
				temp=d.getReciver().loseBoth(d.getReciver().recive());
			}else{
				logger.error(siCmd+"失败，请检查配置");
				throw new Exception(siCmd+"失败，请检查配置");
			}
		}
		return temp;
		
	}
	
	/**
	 * 刷新配置
	 */
	public static void refreshConfig(){
		init();
	}
	
	public EtermConfig getCurrentConfig(){
		return currentConfig;
	}
	
	public static void main(String[] args) {
		Random r=new Random();
		System.out.println(r.nextInt(3));
	}

}
